#pragma once

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>          
#include<iostream>
#include<cstring>
#include <iostream>  
#include <sys/ipc.h>  
#include <sys/types.h>   
#include <sys/shm.h>  
#include"Log.hpp"
using namespace std;

#define Mode 0666
#define FIFE_PIPE "mypipe"
#define SIZE 1024

const string pathname="/home/zcg2/linux-learning/Sharedmemory/Log.hpp";
const int mysize=4097;
const int proj_id=0x4444;

Log log;
key_t Getkey()
{
    key_t key =ftok(pathname.c_str(),proj_id);
    if(key<0)
    {
        log(Fatal,"ftok error:%s",strerror(errno));
        exit(1);
    }
    log(Info,"ftok success, key is:0x%x",key);
    return key;
}

int GetshareMemHelper(int flag)
{
    int shmid=shmget(Getkey(),mysize,flag);
    if(shmid<0)
    {
        log(Fatal,"shemget error:%s",strerror(errno));
        exit(2);
    }
    log(Info,"shmget success, shmid is:%d",shmid);
    return shmid;
}
int GetShm()
{
    return  GetshareMemHelper(IPC_CREAT);
}

int CreateShm()
{
    return  GetshareMemHelper(IPC_CREAT|IPC_EXCL|0666);
}



enum{
    CREATE_ERR=1,
    OPEN_ERR,
    CLOSE_ERR
};

class Init
{
public:
    Init()
    {
        int pip=mkfifo(FIFE_PIPE,Mode);//MODE就是创建什么样的文件
        if(pip<0)
        {
            perror("mkfifo");
            exit(CREATE_ERR);
        }
    }
    ~Init()
    {
        int pip=unlink(FIFE_PIPE);
        if(pip<0)
        {
            perror("mkfifo");
            exit(CLOSE_ERR);
        }
    }
};